<template>
  <div class="min-h-screen bg-gradient-to-br from-green-50 via-white to-emerald-50 flex items-center justify-center px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
      <!-- Logo 和标题 -->
      <div class="text-center">
        <div class="mx-auto h-16 w-16 bg-gradient-to-r from-green-600 to-emerald-600 rounded-full flex items-center justify-center">
          <el-icon :size="28" class="text-white">
            <UserFilled />
          </el-icon>
        </div>
        <h2 class="mt-6 text-3xl font-bold text-gray-900">创建账户</h2>
        <p class="mt-2 text-sm text-gray-600">加入AI角色扮演世界</p>
      </div>

      <!-- 注册表单 -->
      <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-8">
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          size="large"
          @submit.prevent="handleSubmit"
        >
          <!-- 用户名输入 -->
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
              clearable
              class="h-12"
            />
          </el-form-item>

          <!-- 验证方式选择 -->
          <el-form-item>
            <el-radio-group v-model="registerForm.verifyType" class="w-full">
              <el-radio label="email" class="w-1/2">邮箱验证</el-radio>
              <el-radio label="phone" class="w-1/2">手机验证</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 邮箱输入 -->
          <el-form-item v-if="registerForm.verifyType === 'email'" prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱地址"
              :prefix-icon="Message"
              clearable
              class="h-12"
            />
          </el-form-item>

          <!-- 手机号输入 -->
          <el-form-item v-if="registerForm.verifyType === 'phone'" prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号码"
              :prefix-icon="Phone"
              clearable
              class="h-12"
            />
          </el-form-item>

          <!-- 验证码输入 -->
          <el-form-item prop="verifyCode">
            <div class="flex space-x-3">
              <el-input
                v-model="registerForm.verifyCode"
                placeholder="请输入验证码"
                :prefix-icon="Key"
                clearable
                class="h-12 flex-1"
              />
              <el-button
                :disabled="!canSendCode || verifyCodeState.sending"
                :loading="verifyCodeState.sending"
                @click="sendVerificationCode"
                class="h-12 px-6"
              >
                {{
                  verifyCodeState.sending
                    ? '发送中...'
                    : verifyCodeState.countdown > 0
                    ? `${verifyCodeState.countdown}s`
                    : '发送验证码'
                }}
              </el-button>
            </div>
          </el-form-item>

          <!-- 密码输入 -->
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              clearable
              class="h-12"
            />
          </el-form-item>

          <!-- 密码强度指示器 -->
          <div v-if="registerForm.password" class="mb-4">
            <div class="flex items-center justify-between text-xs mb-1">
              <span class="text-gray-500">密码强度</span>
              <span :style="{ color: passwordStrength.color }">{{ passwordStrength.text }}</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-2">
              <div
                class="h-2 rounded-full transition-all duration-300"
                :style="{
                  width: `${(passwordStrength.level / 5) * 100}%`,
                  backgroundColor: passwordStrength.color
                }"
              />
            </div>
          </div>

          <!-- 确认密码输入 -->
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请确认密码"
              :prefix-icon="Lock"
              show-password
              clearable
              class="h-12"
              @keyup.enter="handleSubmit"
            />
          </el-form-item>

          <!-- 用户协议 -->
          <div class="mb-6">
            <el-checkbox v-model="agreeToTerms" class="text-sm text-gray-600">
              我已阅读并同意
              <a href="#" class="text-blue-600 hover:text-blue-500">《用户协议》</a>
              和
              <a href="#" class="text-blue-600 hover:text-blue-500">《隐私政策》</a>
            </el-checkbox>
          </div>

          <!-- 注册按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              :disabled="!agreeToTerms"
              @click="handleSubmit"
              class="w-full h-12 text-base font-medium"
            >
              {{ loading ? '注册中...' : '立即注册' }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 分割线 -->
        <div class="relative my-6">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-gray-300" />
          </div>
          <div class="relative flex justify-center text-sm">
            <span class="px-2 bg-white text-gray-500">或者</span>
          </div>
        </div>

        <!-- 登录链接 -->
        <div class="text-center">
          <span class="text-sm text-gray-600">已有账户？</span>
          <router-link
            to="/login"
            class="ml-1 text-sm text-blue-600 hover:text-blue-500 font-medium transition-colors"
          >
            立即登录
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { UserFilled, User, Message, Phone, Key, Lock } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { validators, getPasswordStrength } from '@/utils/auth'
import type { RegisterForm, VerifyCodeState } from '@/types'

// 路由和状态
const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const registerFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)
const agreeToTerms = ref(false)

// 表单数据
const registerForm = reactive<RegisterForm>({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  verifyCode: '',
  verifyType: 'email'
})

// 验证码状态
const verifyCodeState = reactive<VerifyCodeState>({
  sending: false,
  countdown: 0,
  canSend: true
})

// 计算属性
const canSendCode = computed(() => {
  if (registerForm.verifyType === 'email') {
    return validators.email(registerForm.email) && verifyCodeState.canSend
  } else {
    return validators.phone(registerForm.phone) && verifyCodeState.canSend
  }
})

const passwordStrength = computed(() => {
  return getPasswordStrength(registerForm.password)
})

// 表单验证规则
const registerRules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    },
    {
      min: 3,
      max: 20,
      message: '用户名长度为3-20个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!validators.username(value)) {
          callback(new Error('用户名只能包含字母、数字和下划线'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!validators.email(value)) {
          callback(new Error('请输入有效的邮箱地址'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!validators.phone(value)) {
          callback(new Error('请输入有效的手机号码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  verifyCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!validators.verifyCode(value)) {
          callback(new Error('验证码格式不正确'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 8,
      message: '密码长度不能少于8个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!validators.password(value)) {
          callback(new Error('密码必须包含字母和数字'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认密码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

/**
 * 发送验证码
 */
const sendVerificationCode = async () => {
  if (!canSendCode.value) return

  try {
    verifyCodeState.sending = true

    const account = registerForm.verifyType === 'email' ? registerForm.email : registerForm.phone

    await authStore.sendVerificationCode({
      account,
      type: registerForm.verifyType
    })

    // 开始倒计时
    startCountdown()

  } catch (error) {
    // 错误处理已在store中完成
    console.error('Send verification code failed:', error)
  } finally {
    verifyCodeState.sending = false
  }
}

/**
 * 开始倒计时
 */
const startCountdown = () => {
  verifyCodeState.countdown = 60
  verifyCodeState.canSend = false

  const timer = setInterval(() => {
    verifyCodeState.countdown--
    
    if (verifyCodeState.countdown <= 0) {
      clearInterval(timer)
      verifyCodeState.canSend = true
    }
  }, 1000)
}

/**
 * 处理表单提交
 */
const handleSubmit = async () => {
  if (!registerFormRef.value) return

  try {
    // 表单验证
    await registerFormRef.value.validate()
    
    if (!agreeToTerms.value) {
      ElMessage.warning('请先同意用户协议和隐私政策')
      return
    }

    loading.value = true

    // 执行注册
    await authStore.register(registerForm)

    // 注册成功，跳转到登录页
    ElMessage.success('注册成功，即将跳转到登录页')
    
    setTimeout(() => {
      router.push({
        path: '/login',
        query: { account: registerForm.verifyType === 'email' ? registerForm.email : registerForm.phone }
      })
    }, 1500)

  } catch (error) {
    // 错误处理已在store中完成
    console.error('Register failed:', error)
  } finally {
    loading.value = false
  }
}

// 监听验证类型变化，清空对应字段
watch(
  () => registerForm.verifyType,
  (newType) => {
    if (newType === 'email') {
      registerForm.phone = ''
    } else {
      registerForm.email = ''
    }
    registerForm.verifyCode = ''
  }
)

// 监听密码变化，清空确认密码
watch(
  () => registerForm.password,
  () => {
    if (registerForm.confirmPassword) {
      registerForm.confirmPassword = ''
    }
  }
)
</script>

<style scoped>
/* 自定义样式 */
.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  border-radius: 8px;
}

.el-button {
  border-radius: 8px;
  font-weight: 500;
}

.el-radio-group {
  display: flex;
  justify-content: space-between;
}

.el-radio {
  margin-right: 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .max-w-md {
    max-width: 100%;
    margin: 0 16px;
  }
  
  .bg-white {
    padding: 24px;
  }
  
  .flex.space-x-3 {
    flex-direction: column;
    space-x: 0;
  }
  
  .flex.space-x-3 > * + * {
    margin-left: 0;
    margin-top: 12px;
  }
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 输入框聚焦效果 */
.el-input:focus-within {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.15);
  transition: all 0.2s ease;
}

/* 按钮悬停效果 */
.el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(34, 197, 94, 0.4);
  transition: all 0.2s ease;
}

/* 链接悬停效果 */
a {
  transition: all 0.2s ease;
}

a:hover {
  text-decoration: none;
}

/* 密码强度条动画 */
.transition-all {
  transition: all 0.3s ease;
}
</style>
